<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        .container {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
        }
        .status {
            padding: 10px;
            border-radius: 3px;
            margin-bottom: 15px;
        }
        .status.offline {
            background-color: #ffeeee;
            color: #cc0000;
        }
        .status.online {
            background-color: #eeffee;
            color: #006600;
        }
        .log-container {
            border: 1px solid #ddd;
            border-radius: 3px;
            height: 300px;
            overflow-y: auto;
            padding: 10px;
            background-color: #f9f9f9;
            font-family: monospace;
            font-size: 14px;
        }
        .controls {
            margin-top: 15px;
        }
        input[type="text"] {
            width: 70%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .token-input {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket连接测试工具</h1>
        
        <div class="token-input">
            <label for="token">Token (可选，如果服务器需要认证):</label><br>
            <input type="text" id="token" placeholder="输入您的认证token">
        </div>
        
        <div class="status offline" id="connectionStatus">
            连接状态: 未连接
        </div>
        
        <div class="controls">
            <button id="connectBtn">连接</button>
            <button id="disconnectBtn" disabled>断开连接</button>
        </div>
    </div>
    
    <div class="container">
        <h2>消息发送</h2>
        <div class="controls">
            <input type="text" id="messageInput" placeholder="输入要发送的消息" disabled>
            <button id="sendBtn" disabled>发送</button>
        </div>
    </div>
    
    <div class="container">
        <h2>连接日志</h2>
        <div class="log-container" id="logContainer">
            <div>日志将显示在这里...</div>
        </div>
    </div>

  <script src="https://cdn.socket.io/4.7.2/socket.io.min.js" crossorigin="anonymous"></script>
    
    <script>
    // 获取DOM元素（保持不变）
    const connectionStatus = document.getElementById('connectionStatus');
    const logContainer = document.getElementById('logContainer');
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    const messageInput = document.getElementById('messageInput');
    const sendBtn = document.getElementById('sendBtn');
    const tokenInput = document.getElementById('token');
    
    let socket = null;
    
    // 添加日志到日志容器
    function addLog(message) {
        const logEntry = document.createElement('div');
        logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
        logContainer.appendChild(logEntry);
        logContainer.scrollTop = logContainer.scrollHeight;
    }
    
    // 连接WebSocket服务器
    // 在connect函数中增强错误处理
    function connect() {
        const token = tokenInput.value.trim();
        
        try {
            addLog(`尝试连接到: ws://localhost:3000`);
            addLog(`使用的Token: ${token ? token.substring(0, 20) + '...' : '无'}`);
            
            // 创建Socket.IO连接
            socket = io('ws://localhost:3000', {
                query: { token },
                transports: ['websocket'],
                // 增加额外的调试信息
                reconnection: false,
                autoConnect: true
            });
            
            // 连接尝试开始
            addLog(`Socket.IO连接请求已发送，等待响应...`);
            
            // 连接打开事件
            socket.on('connect', function() {
                addLog('🎉 连接已成功打开！');
                connectionStatus.textContent = '连接状态: 已连接';
                connectionStatus.className = 'status online';
                
                // 更新按钮状态
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
                messageInput.disabled = false;
                sendBtn.disabled = false;
                
                // 发送一个测试消息
                socket.emit('ping-test', { timestamp: Date.now() });
                addLog('已发送心跳测试消息');
            });
            
            // 接收消息事件
            socket.on('message', function(data) {
                addLog(`收到消息: ${JSON.stringify(data)}`);
            });
            
            // 认证成功事件
            socket.on('auth-success', function(data) {
                addLog(`认证成功: ${JSON.stringify(data)}`);
            });
            
            // 认证失败事件
            socket.on('auth-error', function(error) {
                addLog(`认证失败: ${error.message || JSON.stringify(error)}`);
            });
            
            // 心跳响应
            socket.on('pong-test', function(data) {
                addLog(`收到心跳响应: ${JSON.stringify(data)}`);
            });
            
            // 连接错误事件
            socket.on('error', function(error) {
                addLog(`连接错误: ${error.message || JSON.stringify(error)}`);
            });
            
            // 连接关闭事件
            socket.on('disconnect', function(reason) {
                addLog(`连接已关闭，原因: ${reason}`);
                connectionStatus.textContent = '连接状态: 未连接';
                connectionStatus.className = 'status offline';
                
                // 更新按钮状态
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                messageInput.disabled = true;
                sendBtn.disabled = true;
            });
        } catch (error) {
            addLog(`🚨 创建连接失败: ${error.message}`);
            addLog(`错误详情: ${JSON.stringify(error)}`);
        }
    }
    
    // 断开WebSocket连接
    function disconnect() {
        if (socket) {
            socket.disconnect();
            socket = null;
        }
    }
    
    // 发送消息
    function sendMessage() {
        const message = messageInput.value.trim();
        if (socket && message) {
            socket.emit('message', message);
            addLog(`已发送: ${message}`);
            messageInput.value = '';
        }
    }
    
    // 添加事件监听器
    connectBtn.addEventListener('click', connect);
    disconnectBtn.addEventListener('click', disconnect);
    sendBtn.addEventListener('click', sendMessage);
    messageInput.addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            sendMessage();
        }
    });
    
    // 页面加载完成时添加初始日志
    addLog('WebSocket测试工具已加载');
    addLog('点击"连接"按钮开始测试');
    </script>
</body>
</html>